package com.glodon.paas.activity.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.glodon.paas.activity.api.bean.Activity;
import com.glodon.paas.activity.api.bean.ActivityDefinition;
import com.glodon.paas.activity.biz.ActivityDefinitionBiz;
import com.glodon.paas.activity.biz.AppInfoBiz;
import com.glodon.paas.activity.dao.domain.ActivityDefinitionEntity;
import com.glodon.paas.activity.dao.domain.AppInfoEntity;
import com.glodon.paas.activity.resource.internal.ActivityInternalResource;
import com.glodon.paas.activity.util.ActivityDefinitionHelp;
import com.glodon.paas.consts.StringConst;

@Controller
@RequestMapping("/activityDefinition")
public class ActivityDefinitionController {

    public static final Logger LOGGER   = LoggerFactory.getLogger(ActivityDefinitionController.class);
    public static String       PAGE_PRE = "activityDefinition/";

    @Autowired
    ActivityDefinitionBiz      activityDefinitionBiz;
    @Autowired
    ActivityInternalResource   activityInternalResource;
    @Autowired
    AppInfoBiz                 appInfoBiz;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView index() {
        
        LOGGER.debug("index()");
        
        // return new ModelAndView(new RedirectView("list"));
        return new ModelAndView(PAGE_PRE + "index");
    }

    @RequestMapping(value = "pageAppSelect", method = RequestMethod.GET)
    public ModelAndView pageAppSelect(
                        HttpServletRequest request,
                        @RequestParam(value = "appId", defaultValue = "0") Integer appId,
                        ModelMap model
                        ) {
        
        LOGGER.debug("pageAppSelect()");
        // 用于下拉菜单
        List<AppInfoEntity> appInfoList = appInfoBiz.selectAll();
        model.addAttribute("appInfoList", appInfoList);
        return new ModelAndView(PAGE_PRE + "app_select");
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(
                        HttpServletRequest request,
                        @RequestParam(value = "appId", defaultValue = "0") Integer appId,
                        ModelMap model
                        ) {
        
        LOGGER.debug("list()");
        
        if (appId == null) {
            appId = 0;
        }

        // 查询appId下所有定义
        if (appId != 0) {
            List<ActivityDefinitionEntity> list = activityDefinitionBiz.selectByAppId(appId);
            model.addAttribute(StringConst.ITEMS, ActivityDefinitionHelp.toActivityDefinition(list));
        }
        return new ModelAndView(PAGE_PRE + "list");
    }

    @RequestMapping(value = "testTemplate", method = RequestMethod.POST)
    public ModelAndView testTemplate(
                        HttpServletRequest request,
                        ActivityDefinition item,
                        ModelMap model
                        ) {
        
        LOGGER.debug("testTemplate()");
        
        String template = item.getTemplate();
        String activityJson = item.getTestActivityJson();

        Activity activity = null;
        String returnMsg = null;
        try {
            activity = JSON.parseObject(activityJson, Activity.class);
        } catch (Exception e) {
            returnMsg = "activity数据转换异常" + e.getMessage();
            LOGGER.error(returnMsg, e);
        }

        if (returnMsg == null) {
            try {
                String def = activityInternalResource.testTemplate(template, activity);
                model.addAttribute(StringConst.RESULT, def);
            } catch (Exception e) {
                returnMsg = "模版匹配异常" + e.getMessage();
                LOGGER.error(returnMsg, e);
            }
        }

        if (returnMsg != null) {
            model.addAttribute(StringConst.RETURN_MSG, returnMsg);
        }
        return new ModelAndView(PAGE_PRE + "template_test");
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ModelAndView saveDefinition(
                         HttpServletRequest request,
                         ActivityDefinition item,
                         @RequestParam(value = "update", defaultValue = "0") int update,
                         ModelMap model
                         ) {
        
        LOGGER.debug("saveDefinition()");
        
        String returnMsg = null;
        if (update == 1) {
            ActivityDefinition itemDB = activityInternalResource.updateDefinition(request, item);
            if (itemDB == null) {
                returnMsg = "数据不存在";
            } else {
                item = itemDB;
            }
        } else {
            try {
                item = activityInternalResource.addDefinition(request, item);
            } catch (Exception e) {
                returnMsg = e.getMessage();
            }
        }

        model.addAttribute("item", item);
        model.addAttribute("update", update);
        model.addAttribute("returnMsg", returnMsg);

        // 查询appId下所有定义
        return new ModelAndView(PAGE_PRE + "edit");
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public ModelAndView delete(
                        HttpServletRequest request,
                        @RequestParam(value = "activityType", required = false)Long activityType,
                        ModelMap model
                        ) {
        
        LOGGER.debug("delete()");
        
        Integer appId = 0;
        ActivityDefinitionEntity db = activityDefinitionBiz.selectById(activityType);
        if (db != null) {
            appId = db.getAppId();
        }
        activityDefinitionBiz.deleteById(activityType);
        // 查询appId下所有定义
        return list(request, appId, model);
    }

    @RequestMapping(value = "get", method = RequestMethod.GET)
    public ModelAndView get(
                        HttpServletRequest request,
                        @RequestParam(value = "activityType", defaultValue = "0") Long activityType,
                        ModelMap model) {
        
        LOGGER.debug("get()");
        
        ActivityDefinitionEntity entity = activityDefinitionBiz.selectById(activityType);
        model.addAttribute("item", entity);
        return new ModelAndView(PAGE_PRE + "edit");
    }

    @RequestMapping(value = "new", method = RequestMethod.GET)
    public ModelAndView newPage(
                        HttpServletRequest request,
                        @RequestParam(value = "appId", defaultValue = "0") Integer appId,
                        ModelMap model
                        ) {
        
        LOGGER.debug("newPage()");
        
        ActivityDefinitionEntity entity = new ActivityDefinitionEntity();
        entity.setAppId(appId);
        entity.setModelId(0);
        entity.resetActivityType();
        model.addAttribute("item", entity);
        return new ModelAndView(PAGE_PRE + "edit");
    }

    @RequestMapping(value = "/listApp", method = RequestMethod.GET)
    public ModelAndView listApp(ModelMap model) {
        
        LOGGER.debug("listApp()");
        
        List<AppInfoEntity> list = appInfoBiz.selectAll();
        model.addAttribute(StringConst.ITEMS, list);
        return new ModelAndView(PAGE_PRE + "app_list");
    }

    @RequestMapping(value = "saveApp", method = RequestMethod.POST)
    public ModelAndView saveApp(
                        HttpServletRequest request,
                        @RequestParam(value = "appId", required = true) Integer appId,
                        @RequestParam(value = "displayName", required = true) String displayName,
                        @RequestParam(value = "description", required = true) String description,
                        @RequestParam(value = "update", required = false, defaultValue = "0") int update,
                        ModelMap model
                        ) {
        
        LOGGER.debug("saveApp()");
        
        String returnPage = PAGE_PRE + "app_list";
        model.put("errorMsg", null);
        model.put("appId", appId);
        model.put("displayName", displayName);
        model.put("description", description);
        model.put("update", update);

        if (appId == null) {
            model.addAttribute("errorMsg", "appId不能空");
            return new ModelAndView(returnPage);
        }

        if (displayName == null) {
            model.addAttribute("errorMsg", "名称不能空");
            return new ModelAndView(returnPage);
        }

        AppInfoEntity entity = appInfoBiz.selectById(appId);
        if (entity != null) {
            if (update == 1) {
                entity.setDescription(description);
                entity.setDisplayName(displayName);
                appInfoBiz.updateById(entity);
            } else {
                model.addAttribute("errorMsg", "app 已存在");
            }
        } else if (entity == null) {
            entity = new AppInfoEntity();
            entity.setAppId(appId);
            entity.setDisplayName(displayName);
            entity.setDescription(description);
            appInfoBiz.insert(entity);
        }
        List<AppInfoEntity> list = appInfoBiz.selectAll();
        model.addAttribute(StringConst.ITEMS, list);
        return new ModelAndView(PAGE_PRE + "app_list");
    }
}
